/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo08.util;

import javax.servlet.http.HttpServletRequest;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/24 11:57
 */
public class LoggerUtils {
    public static final String LOGGER_RETURN = "_logger_return";

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

    /**
     * 返回请求类型 （ajax|普通请求）
     *
     * @param request HttpServletRequest
     * @return String
     */
    public static String getRequestType(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return isBlank(header)?"普通请求":"ajax";
    }
}
